$(function () {
    var $form = $("form");
    var $login = $("#login");
    var validate = $form.validate();
    function login() {
        $login.off("click").addClass("disabled").html("<span class='fa fa-pulse fa-spinner'></span>正在登录");
        if (validate.form()) {
            var url = $form.attr("action");
            $.post(url, $form.serialize(), function (data) {
                if (data['code'] && data['code'] !== "0") { //登录失败
                    if (data['code'] === "1001") {
                        $("#username").closest(".form-group").removeClass("has-success").addClass('has-error');
                    } else if (data['code'] === "1002") {
                        $("#password").closest(".form-group").removeClass("has-success").addClass('has-error');
                    }
                    var errorAlertHtml = [];
                    errorAlertHtml.push('<div class="alert alert-danger alert-dismissible fade in" role="alert">');
                    errorAlertHtml.push('  <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span></button>');
                    errorAlertHtml.push('  <span>' + data['msg'] + '</span>');
                    errorAlertHtml.push('</div>');
                    $form.find("div.alert").remove();
                    $form.prepend($(errorAlertHtml.join("")));
                    $("#login").on("click", login).removeClass("disabled").html("登录");
                } else { //登录成功
                    window.location.href = NOTE_PAGE;
                }
            });
        } else {
            $login.removeClass("disabled").html("登录").on("click", login);
        }
    }
    $login.on("click", login);
});